<template>
  <div class="MusicScoreManage-container">
    <div class="MusicScoreManage-options">
      <el-input
        placeholder="请输入内容"
        style="width:60%;"
        @change="SearchMusicScores"
        v-model="content"
      >
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-button
        type="primary"
        style="margin-left:20px"
        @click="publishMusicScore"
        >添加乐谱</el-button
      >
      <el-button
        style="margin-left:20px"
        type="warning"
        @click="OpenDeleteListDialog"
        >待删除列表</el-button
      >
      <el-button type="info" @click="BatchDownload">批量下载</el-button>

      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>
    <div class="MusicScoreManage-table" v-if="musicScoreList.length">
      <el-table
        :data="musicScoreList"
        border
        @selection-change="handleSelectionChange"
        max-height="80%"
        :default-sort="{ prop: 'date', order: 'descending' }"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="创建日期" sortable width="180">
          <template slot-scope="scope">
            <svg-icon icon-class="date"></svg-icon>
            <span style="margin-left: 10px">{{
              scope.row.create_time | formatDate
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标题" width="100">
          <template slot-scope="scope">
            <el-popover trigger="click" placement="top">
              <div class="tagList" v-if="tagList.length">
                所有标签:
                <el-tag type="info" v-for="t in tagList" :key="t.id">
                  {{ t.tag_name }}
                </el-tag>
              </div>
              <div class="tagList" v-else>
                暂无任何标签
              </div>
              <div slot="reference" class="name-wrapper">
                <el-tag
                  @click="getMusicScoreTags(scope.row.id)"
                  size="medium"
                  >{{ scope.row.music_score_title }}</el-tag
                >
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="内容">
          <template slot-scope="scope">
            <span>{{ scope.row.music_score_abstract }}</span>
          </template>
        </el-table-column>
        <el-table-column label="价格">
          <template slot-scope="scope">
            <span>{{ scope.row.cost ? scope.row.cost : 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否付费" width="50">
          <template slot-scope="scope">
            <span>{{ scope.row.paid_product ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="封面">
          <template slot-scope="scope">
            <img :src="scope.row.img_url" style="width:100px" />
          </template>
        </el-table-column>
        <el-table-column label="乐谱所在文件夹" width="60">
          <template slot-scope="scope">
            <span>{{ scope.row.file_code }}</span>
          </template>
        </el-table-column>
        <el-table-column label="喜欢数" width="60">
          <template slot-scope="scope">
            <span>{{ scope.row.like_count }}</span>
          </template>
        </el-table-column>

        <el-table-column label="评论数" width="60">
          <template slot-scope="scope">
            <span>{{ scope.row.comment_count }}</span>
          </template>
        </el-table-column>
        <el-table-column label="浏览数" width="60">
          <template slot-scope="scope">
            <span>{{ scope.row.view_count }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div class="options">
              <el-button
                size="mini"
                class="optionBtn"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                class="optionBtn"
                @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="handleDownload(scope.$index, scope.row)"
                >下载</el-button
              >
              <el-button
                size="mini"
                type="info"
                class="optionBtn"
                @click="handlePaidList(scope.$index, scope.row)"
                >查看已购买名单</el-button
              >
              <el-button
                size="mini"
                type="info"
                class="optionBtn"
                @click="addPaidMember(scope.$index, scope.row)"
                >添加支付名额</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        small
        :limit="limit"
        :page-size="limit"
        :current-page="page"
        @current-change="pageChange"
        layout="prev, pager, next"
        :total="count"
      >
      </el-pagination>
    </div>
    <div v-else style="display:flex;justify-content:center">
      <img
        style="width:50%;margin:0 auto"
        src="@/assets/img/search-empty.png"
      />
    </div>
    <PublishDialog
      :data="EditForm"
      type="musicScore"
      dialogTitle="编辑乐谱"
      :visible="EditDialogVisible"
      @custom-confirm="EditConfirm"
      @custom-close="EditDialogClose"
    />
    <PublishDialog
      :data="publishForm"
      type="musicScore"
      dialogTitle="添加乐谱"
      :visible="PublishDialogVisible"
      @custom-confirm="PublishConfirm"
      @custom-close="PublishDialogClose"
    />
    <PurCharseListDialog
      :visible="PurCharseListDialogVisible"
      dialogTitle="已购买名单"
      :musicScoreId="currentMusicScoreId"
      @custom-close="PurChaseListClose"
    />
    <AddPucharseMemberDialog
      dialogTitle="添加支付名额"
      :musicScoreId="currentMusicScoreId"
      :visible="AddPucharseMemberDialogVisible"
      @custom-confirm="AddPucharseMemberConfirm"
      @custom-close="AddPucharseMemberClose"
    />
    <!-- 删除列表对话框 -->
    <DeleteListDialog
      :data="DeleteList"
      dialogTitle="删除乐谱列表"
      :pageSize="pageSize"
      :total="total"
      type="music_score"
      @custom-reload="getDeleteList"
      @current-page-change="DeleteListPageChange"
      :visible="DeleteListDialogVisible"
      @custom-close="DeleteListDialogClose"
    />
  </div>
</template>

<script>
import { encryptData } from '@/utils/encrypt'
import EditDialog from '@/components/Dialog/EditDialog'
import PublishDialog from '@/components/Dialog/PublishDialog'
import PurCharseListDialog from '@/components/Dialog/PurCharseListDialog'
import AddPucharseMemberDialog from '@/components/Dialog/AddPucharseMemberDialog'
import DeleteListDialog from '@/components/Dialog/DeleteListDialog'
import {
  downLoadFile,
  BatchDownloadFiles,
  downLoadFileOrFolder,
  downLoadFileByPrefix
} from '@/api/cos'
import { saveAs } from 'file-saver'
import JSZip from 'jszip'
import { arrayBufferToBase64 } from '@/utils'

export default {
  // 引入组件
  components: {
    EditDialog,
    PublishDialog,
    PurCharseListDialog,
    AddPucharseMemberDialog,
    DeleteListDialog
  },
  data() {
    return {
      limit: 3,
      page: 1,
      // 权限数据
      tagList: [],
      isEdit: false,
      count: 0,
      // 乐谱列表
      musicScoreList: [],
      content: '',
      // 编辑数据
      EditDialogVisible: false,
      formLabelWidth: '80px',
      // 编辑表单
      EditForm: {},
      // 添加表单
      publishForm: {
        title: '',
        content: '',
        cost: '',
        paid_product: false
      },
      // 添加乐谱窗口显示标志位
      PublishDialogVisible: false,
      // 当前查看购买列表id
      currentMusicScoreId: null,
      // 支付名单对话框显示标志位
      PurCharseListDialogVisible: false,
      // 添加支付名额
      AddPucharseMemberDialogVisible: false,
      selectedMusicScores: '',
      DeleteListDialogVisible: false,
      DeleteList: [], // 已删除列表
      // 删除列表分页信息
      pageSize: 3,
      currentPage: 1,
      total: null,
      downloadLink: null, // 下载链接
      loading: false // 下载loading
    }
  },
  created() {
    // 获取乐谱列表
    this.$nextTick(() => {
      this.getMusicScoreList()
    })
  },
  methods: {
    // 批量视频下载
    BatchDownload() {
      this.$confirm('是否下载选中的视频文件?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.loading = true
          const regex = /\/([^/]+)$/

          let urls = this.selectedMusicScores.map(item => {
            if (item.file_code) {
              return item.file_code
            }
          })

          let completedCount = 0 // 已完成下载的文件数量

          // 移除之前创建的 <a> 标签
          if (this.downloadLink) {
            document.body.removeChild(this.downloadLink)
            this.downloadLink = null
          }

          for (let i = 0; i < urls.length; i++) {
            const url = urls[i]
            const response = await downLoadFileOrFolder('musicScore/' + urls[i])

            if (response) {
              const fileData = response.Body

              // 创建新的 <a> 标签用于触发下载
              this.downloadLink = document.createElement('a')
              this.downloadLink.href = URL.createObjectURL(fileData)
              this.downloadLink.download = decodeURIComponent(url) // 设置下载文件的名称
              this.downloadLink.style.display = 'none'

              // 将 <a> 标签添加到 DOM 中
              document.body.appendChild(this.downloadLink)

              // 触发下载
              this.downloadLink.click()

              completedCount++

              // 更新下载进度
              this.$message({
                type: 'info',
                message: `已下载 ${completedCount} / ${urls.length} 个文件`
              })
            }
          }

          this.loading = false

          this.$message({
            type: 'success',
            message: '下载成功！'
          })
        })
        .catch(err => {
          console.log(err)
          this.$message({
            type: 'info',
            message: '已取消下载'
          })
        })
    },
    // 视频下载
    async handleDownload(index, musicScore) {
      this.$confirm('是否下载该文件夹?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.loading = true

          // 移除之前创建的 <a> 标签
          if (this.downloadLink) {
            document.body.removeChild(this.downloadLink)
            this.downloadLink = null
          }
          let completedCount = 0 // 已完成下载的文件数量

          const response = await downLoadFileOrFolder(
            'musicScore/' + musicScore.file_code
          )
          let zip = new JSZip()
          console.log(response)
          for (let i = 0; i < response.length; i++) {
            if (response) {
              let fileData = response[i].data.Body
              zip.file(response[i].key, fileData) // 使用文件名作为参数
              completedCount++

              // 更新下载进度
              this.$message({
                type: 'info',
                message: `已下载 ${completedCount} / ${response.length} 个文件`
              })
            }
          }

          // 生成 ZIP 压缩包
          zip
            .generateAsync({ type: 'blob' })
            .then(blob => {
              // 创建新的 <a> 标签用于触发下载
              this.downloadLink = document.createElement('a')
              this.downloadLink.href = URL.createObjectURL(blob)
              this.downloadLink.download = decodeURIComponent(
                musicScore.file_code + '.zip'
              ) // 设置下载文件的名称
              this.downloadLink.style.display = 'none'

              // 将 <a> 标签添加到 DOM 中
              document.body.appendChild(this.downloadLink)

              // 触发下载
              this.downloadLink.click()

              this.loading = false

              this.$message({
                type: 'success',
                message: '下载成功!'
              })
            })
            .catch(err => {
              console.log(err)
              this.$message({
                type: 'warning',
                message: '下载失败'
              })
              this.loading = false
            })
        })
        .catch(err => {
          console.log(err)
          this.$message({
            type: 'warning',
            message: '下载失败'
          })
          this.loading = false
        })
    },

    // 关闭已删除列表回调
    DeleteListDialogClose() {
      // 重新获取文章列表
      this.getMusicScoreList().then(() => {
        this.DeleteListDialogVisible = false
      })
    },
    // 打开待删除列表
    OpenDeleteListDialog() {
      this.getDeleteList()
        .then(() => {
          this.DeleteListDialogVisible = true
        })
        .catch(error => {
          console.log(error)
          this.$message.error('获取已删除列表失败')
        })
    },
    // 获取已删除列表
    async getDeleteList() {
      const { pageSize, currentPage } = this
      const res = await this.$API.musicScore.getMusicScoreDeleteList(
        pageSize,
        currentPage
      )
      // 如果未获取到数据就退回一页重新获取数据
      if (res && !res.data) {
        if (currentPage <= 1) {
          return (this.DeleteList = [])
        } else {
          this.currentPage--
          this.getDeleteList()
        }
      }
      if (res.status == 200) {
        this.DeleteList = res.data.payload
        this.total = res.data.count
      } else {
        return this.$message.error('获取以删除列表失败')
      }
    },
    // 已删除列表页数改变
    DeleteListPageChange(currentPage) {
      this.currentPage = currentPage
      // 重新获取列表
      this.getDeleteList()
    },
    // 添加支付名单窗口关闭回调
    AddPucharseMemberClose() {
      this.AddPucharseMemberDialogVisible = false
    },
    // 添加支付名单确认回调
    AddPucharseMemberConfirm() {},
    // 打开添加购买用户名单
    addPaidMember(index, musicScore) {
      this.currentMusicScoreId = musicScore.id
      this.AddPucharseMemberDialogVisible = true
    },
    // 关闭购买列表回调
    PurChaseListClose() {
      this.PurCharseListDialogVisible = false
    },
    // 进入支付名单对话框
    handlePaidList(index, musicScore) {
      this.currentMusicScoreId = musicScore.id

      this.PurCharseListDialogVisible = true
    },
    // 获取乐谱列表
    async getMusicScoreList() {
      const { limit, page } = this
      // 如果处于搜索状态就继续搜索
      if (this.content) {
        this.SearchMusicScores()
      }
      const res = await this.$API.musicScore.getMusicScoreList(limit, page)
      if (res.status == 200) {
        this.count = res.data.count
        this.musicScoreList = res.data.payload
      }
    },
    // 页数改变
    pageChange(page) {
      // console.log('page', page)
      this.page = page
      this.getMusicScoreList()
    },
    // 添加乐谱确认功能回调
    async PublishConfirm(formData) {
      // 整理数据
      const datas = this.$qs.stringify(formData, { arrayFormat: 'brackets' })
      const res = await this.$API.musicScore.publishMusicScore(datas)
      if (res.status == 200) {
        this.$message.success('添加成功')
        // 初始化数据
        this.PublishDialogVisible = false
        this.content = ''
        this.getMusicScoreList()
      }
    },
    // 添加乐谱窗口关闭回调
    PublishDialogClose() {
      this.PublishDialogVisible = false
    },
    // 编辑乐谱
    async handleEdit(id, musicScore) {
      console.log(musicScore)
      // 获取乐谱详情内容
      const res = await this.$API.musicScore.RefreshMusicScore(musicScore.id)
      console.log(res)
      if (res.status == 200) {
        // 整理数据
        let datas = {
          music_score_id: musicScore.id,
          title: musicScore.music_score_title,
          content: res.data.content,
          img_url: musicScore.img_url,
          cost: musicScore.cost,
          paid_product: musicScore.paid_product,
          imgList: res.data.referenceds
        }
        // 获取数据
        this.EditForm = datas
        this.EditDialogVisible = true
      } else {
        this.$messager.error('该乐谱不存在')
      }
    },
    // 删除乐谱
    handleDelete(id, musicScore) {
      this.$confirm('此操作将永久删除该乐谱, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const datas = new FormData()
          datas.append('music_score_id', musicScore.id)
          const res = await this.$API.musicScore.deleteMusicScore(datas)
          if (res.status == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 初始化数据
            this.getMusicScoreList()
            this.content = ''
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 搜索乐谱
    async SearchMusicScores() {
      this.page = 1
      const { content, page, limit } = this
      console.log(content, page, limit)
      // 如果不存在搜索内容就获取全部
      if (!this.content) return this.getMusicScoreList()
      const res = await this.$API.musicScore.SearchMusicScores(
        content,
        limit,
        page
      )
      // 如果不存在乐谱就显示空
      if (!res.data) this.musicScoreList = []
      console.log(res)
      if (res.status == 200) {
        this.musicScoreList = res.data.payload
        this.count = res.data.count
      }
    },
    // 关闭对话框
    EditDialogClose() {
      this.EditDialogVisible = false
    },
    // 确定编辑
    async EditConfirm(formData) {
      // 整理数据
      let { id } = formData
      const datas = {
        ...formData
      }
      const res = await this.$API.musicScore.EditMusicScore(
        this.$qs.stringify(datas, { arrayFormat: 'brackets' })
      )
      if (res.status == 200) {
        this.$message.success('编辑成功')
        // 初始化数据
        this.EditDialogVisible = false
        this.content = ''

        this.getMusicScoreList()
        this.EditForm = {}
      } else {
        this.$message.error('编辑失败')
      }
    },
    // 添加乐谱
    publishMusicScore() {
      this.publishForm = {
        title: '',
        content: '',
        cost: '',
        paid_product: false
      }
      this.PublishDialogVisible = true
    },
    // 通过乐谱id获取用户的权限
    async getMusicScoreTags(id) {
      this.tagList = []
      const res = await this.$API.tag.getMusicScoreTags(id)
      // 如果不存在权限就将权限列表清空
      if (!res.data) return (this.tagList = [])
      if (res.status == 200) {
        this.tagList = res.data
      }
    },
    // 多选项切换时
    handleSelectionChange(selection) {
      this.selectedMusicScores = selection
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedMusicScores.length === 0) {
        this.$message.warning('请选择要删除的乐谱')
        return
      }

      this.$confirm('此操作将永久删除选中的乐谱, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const musicScoreIds = this.selectedMusicScores.map(
            musicScore => musicScore.id
          )
          const formData = new FormData()
          formData.append('music_score_ids', musicScoreIds.join(','))
          const res = await this.$API.musicScore.BatchDeleteMusicScore(formData)
          if (res.status === 200) {
            this.$message.success('批量删除成功')
            this.getMusicScoreList()
            this.content = ''
            this.selectedMusicScores = []
          } else {
            this.$message.error('批量删除失败')
          }
        })
        .catch(() => {
          this.$message.info('已取消批量删除')
        })
    }
  }
}
</script>
<style scoped>
.MusicScoreManage-container {
  width: 100%;
  padding: 20px;
}
.MusicScoreManage-options {
  margin-bottom: 20px;
}
.MusicScoreManage-table {
  width: 100%;
  margin: 10px auto;
}
.options {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  padding: 5px;
}
.optionBtn {
  margin: 5px;
}
</style>